import csv
from django.core.management.base import BaseCommand
from stock_app.models import StockData

class Command(BaseCommand):
    help = 'Import stock data from CSV'

    def handle(self, *args, **kwargs):
        try:
            with open('stock601939.csv', newline='') as csvfile:
                reader = csv.DictReader(csvfile)
                for row in reader:
                    print(f"Processing row: {row}")  # 打印当前行
                    StockData.objects.create(
                        ts_code=row['ts_code'],
                        trade_date=row['trade_date'],
                        open=float(row['open']),
                        high=float(row['high']),
                        low=float(row['low']),
                        close=float(row['close']),
                        pre_close=float(row['pre_close']),
                        change=float(row['change']),
                        pct_chg=float(row['pct_chg']),
                        vol=float(row['vol']),
                        amount=float(row['amount'])
                    )
            self.stdout.write(self.style.SUCCESS('Successfully imported stock data'))
        except Exception as e:
            self.stdout.write(self.style.ERROR(f'Error: {e}'))